// 模拟后端数据（实际项目中通过API请求获取）
const mockData = {
    friends: [
        { id: 1, name: "张三", avatar: "https://picsum.photos/seed/friend1/100/100" },
        { id: 2, name: "李四", avatar: "https://picsum.photos/seed/friend2/100/100" },
        { id: 3, name: "王五", avatar: "https://picsum.photos/seed/friend3/100/100" },
        { id: 4, name: "赵六", avatar: "https://picsum.photos/seed/friend4/100/100" },
        { id: 5, name: "孙七", avatar: "https://picsum.photos/seed/friend5/100/100" },
        { id: 6, name: "周八", avatar: "https://picsum.photos/seed/friend6/100/100" }
    ],
    albums: [
        { id: 1, cover: "https://picsum.photos/seed/album1/200/200", name: "旅行相册" },
        { id: 2, cover: "https://picsum.photos/seed/album2/200/200", name: "生活日常" },
        { id: 3, cover: "https://picsum.photos/seed/album3/200/200", name: "美食记录" },
        { id: 4, cover: "https://picsum.photos/seed/album4/200/200", name: "风景随拍" },
        { id: 5, cover: "https://picsum.photos/seed/album5/200/200", name: "聚会时光" },
        { id: 6, cover: "https://picsum.photos/seed/album6/200/200", name: "学习打卡" }
    ],
    videos: [
        { id: 1, title: "海边日落延时摄影", thumbnail: "https://picsum.photos/seed/video1/400/225", url: "assets/videos/sample.mp4" },
        { id: 2, title: "生日派对精彩瞬间", thumbnail: "https://picsum.photos/seed/video2/400/225", url: "assets/videos/sample.mp4" }
    ],
    logs: [
        { id: 1, title: "2024年旅行总结：那些走过的山川湖海", time: "2024-08-15" },
        { id: 2, title: "学习前端开发的第30天：HTML+CSS实战心得", time: "2024-07-28" },
        { id: 3, title: "夏日美食清单：3道简单又美味的家常菜", time: "2024-06-30" }
    ],
    visitors: [
        { id: 1, name: "小明", avatar: "https://picsum.photos/seed/visitor1/100/100" },
        { id: 2, name: "小红", avatar: "https://picsum.photos/seed/visitor2/100/100" },
        { id: 3, name: "小刚", avatar: "https://picsum.photos/seed/visitor3/100/100" },
        { id: 4, name: "小丽", avatar: "https://picsum.photos/seed/visitor4/100/100" }
    ],
    feeds: [
        {
            id: 1,
            type: "image",
            user: { name: "星辰大海", avatar: "assets/images/avatar.jpg" },
            time: "今天 10:25",
            content: "周末去公园拍的荷花，夏日限定美景 🌸",
            images: [
                "https://picsum.photos/seed/flower1/600/400",
                "https://picsum.photos/seed/flower2/600/400",
                "https://picsum.photos/seed/flower3/600/400"
            ],
            likes: 32,
            comments: 8,
            shares: 2
        },
        {
            id: 2,
            type: "video",
            user: { name: "星辰大海", avatar: "assets/images/avatar.jpg" },
            time: "昨天 18:30",
            content: "分享一段海边日落的延时摄影，治愈所有不开心 🌅",
            video: "assets/videos/sample.mp4",
            thumbnail: "https://picsum.photos/seed/video1/800/450",
            likes: 45,
            comments: 12,
            shares: 5
        },
        {
            id: 3,
            type: "log",
            user: { name: "星辰大海", avatar: "assets/images/avatar.jpg" },
            time: "3天前",
            content: "新写的旅行总结日志已发布，记录了今年走过的那些地方，附上详细攻略～",
            logId: 1,
            likes: 28,
            comments: 15,
            shares: 3
        },
        {
            id: 4,
            type: "text",
            user: { name: "星辰大海", avatar: "assets/images/avatar.jpg" },
            time: "1周前",
            content: "学习前端开发的第30天，终于完成了第一个静态网页项目！虽然过程中有很多困难，但坚持下来真的很有成就感 💪",
            likes: 52,
            comments: 23,
            shares: 1
        }
    ]
};

// 模拟API请求函数
async function fetchData(apiUrl) {
    // 实际项目中替换为真实API地址
    return new Promise((resolve) => {
        setTimeout(() => {
            let data = {};
            switch (apiUrl) {
                case "/api/friends":
                    data = mockData.friends;
                    break;
                case "/api/albums":
                    data = mockData.albums;
                    break;
                case "/api/videos":
                    data = mockData.videos;
                    break;
                case "/api/logs":
                    data = mockData.logs;
                    break;
                case "/api/visitors":
                    data = mockData.visitors;
                    break;
                case "/api/feeds":
                    data = mockData.feeds;
                    break;
            }
            resolve({ success: true, data });
        }, 800);
    });
}

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", async () => {
    // 异步加载各模块数据
    await loadFriends();
    await loadAlbums();
    await loadVideos();
    await loadLogs();
    await loadVisitors();
    await loadFeeds();

    // 绑定标签页切换事件
    bindTabEvents();

    // 绑定发布动态事件
    bindPublishEvent();
});

// 加载好友列表
async function loadFriends() {
    const friendsList = document.getElementById("friendsList");
    const res = await fetchData("/api/friends");
    if (res.success) {
        res.data.forEach(friend => {
            const friendItem = document.createElement("div");
            friendItem.className = "friend-item";
            friendItem.innerHTML = `
                <img src="${friend.avatar}" alt="${friend.name}" class="friend-avatar">
                <span class="friend-name">${friend.name}</span>
            `;
            friendsList.appendChild(friendItem);
        });
    }
}

// 加载相册预览
async function loadAlbums() {
    const albumGrid = document.getElementById("albumGrid");
    const res = await fetchData("/api/albums");
    if (res.success) {
        res.data.forEach(album => {
            const albumItem = document.createElement("div");
            albumItem.className = "album-item";
            albumItem.innerHTML = `<img src="${album.cover}" alt="${album.name}">`;
            albumGrid.appendChild(albumItem);
        });
    }
}

// 加载视频预览
async function loadVideos() {
    const videoList = document.getElementById("videoList");
    const res = await fetchData("/api/videos");
    if (res.success) {
        res.data.forEach(video => {
            const videoItem = document.createElement("div");
            videoItem.className = "video-item";
            videoItem.innerHTML = `
                <img src="${video.thumbnail}" alt="${video.title}" class="video-thumbnail">
                <div class="video-play"><<i class="fas fa-play"></</i></div>
                <span class="video-title">${video.title}</span>
            `;
            videoList.appendChild(videoItem);
        });
    }
}

// 加载日志列表
async function loadLogs() {
    const logList = document.getElementById("logList");
    const res = await fetchData("/api/logs");
    if (res.success) {
        res.data.forEach(log => {
            const logItem = document.createElement("div");
            logItem.className = "log-item";
            logItem.innerHTML = `
                <a href="logs/log${log.id}.html" class="log-title">${log.title}</a>
                <span class="log-time">${log.time}</span>
            `;
            logList.appendChild(logItem);
        });
    }
}

// 加载访客记录
async function loadVisitors() {
    const visitorsList = document.getElementById("visitorsList");
    const res = await fetchData("/api/visitors");
    if (res.success) {
        res.data.forEach(visitor => {
            const visitorItem = document.createElement("div");
            visitorItem.className = "visitor-item";
            visitorItem.innerHTML = `
                <img src="${visitor.avatar}" alt="${visitor.name}" class="visitor-avatar">
                <span class="visitor-name">${visitor.name}</span>
            `;
            visitorsList.appendChild(visitorItem);
        });
    }
}

// 加载动态内容
async function loadFeeds(filter = "all") {
    const feedList = document.getElementById("feedList");
    feedList.innerHTML = '<div class="loading"><<i class="fas fa-spinner fa-spin"></</i> 加载中...</div>';
    
    const res = await fetchData("/api/feeds");
    if (res.success) {
        let feeds = res.data;
        // 根据标签筛选动态
        if (filter !== "all") {
            feeds = feeds.filter(feed => feed.type === filter);
        }

        setTimeout(() => {
            feedList.innerHTML = "";
            if (feeds.length === 0) {
                feedList.innerHTML = '<div style="text-align:center;padding:40px 0;color:#666;">暂无相关动态</div>';
                return;
            }

            feeds.forEach(feed => {
                const feedItem = document.createElement("div");
                feedItem.className = "feed-item";

                // 构建内容部分
                let contentHtml = `<p class="feed-content">${feed.content}</p>`;

                // 图片内容
                if (feed.images && feed.images.length > 0) {
                    contentHtml += '<div class="feed-images">';
                    feed.images.forEach(img => {
                        contentHtml += `<img src="${img}" alt="动态图片" class="feed-image">`;
                    });
                    contentHtml += '</div>';
                }

                // 视频内容
                if (feed.type === "video") {
                    contentHtml += `
                        <video class="feed-video" controls poster="${feed.thumbnail}">
                            <source src="${feed.video}" type="video/mp4">
                            您的浏览器不支持视频播放
                        </video>
                    `;
                }

                // 日志内容（添加跳转链接）
                if (feed.type === "log") {
                    contentHtml += `<a href="logs/log${feed.logId}.html" class="log-link" style="color:#2d7dd2;">查看完整日志 →</a>`;
                }

                // 组装动态项
                feedItem.innerHTML = `
                    <div class="feed-header">
                        <img src="${feed.user.avatar}" alt="${feed.user.name}" class="feed-avatar">
                        <div class="feed-userinfo">
                            <div class="feed-username">${feed.user.name}</div>
                            <div class="feed-time">${feed.time}</div>
                        </div>
                    </div>
                    ${contentHtml}
                    <div class="feed-actions">
                        <button class="action-btn like-btn" data-id="${feed.id}">
                            <<i class="far fa-heart"></</i> 赞 (${feed.likes})
                        </button>
                        <button class="action-btn comment-btn">
                            <<i class="far fa-comment"></</i> 评论 (${feed.comments})
                        </button>
                        <button class="action-btn share-btn">
                            <<i class="far fa-share-square"></</i> 分享 (${feed.shares})
                        </button>
                    </div>
                `;

                feedList.appendChild(feedItem);
            });

            // 绑定点赞事件
            bindLikeEvents();
        }, 500);
    }
}

// 绑定标签页切换事件
function bindTabEvents() {
    const tabBtns = document.querySelectorAll(".tab-btn");
    tabBtns.forEach(btn => {
        btn.addEventListener("click", () => {
            tabBtns.forEach(b => b.classList.remove("active"));
            btn.classList.add("active");
            loadFeeds(btn.dataset.tab);
        });
    });
}

// 绑定点赞事件
function bindLikeEvents() {
    const likeBtns = document.querySelectorAll(".like-btn");
    likeBtns.forEach(btn => {
        btn.addEventListener("click", () => {
            const icon = btn.querySelector("i");
            const text = btn.textContent.trim();
            const count = parseInt(text.match(/\d+/)[0]);

            if (icon.classList.contains("far")) {
                // 未点赞状态
                icon.classList.remove("far");
                icon.classList.add("fas", "text-red-500");
                btn.innerHTML = `<<i class="fas fa-heart"></</i> 赞 (${count + 1})`;
                btn.style.color = "#e53e3e";
            } else {
                // 已点赞状态
                icon.classList.remove("fas", "text-red-500");
                icon.classList.add("far");
                btn.innerHTML = `<<i class="far fa-heart"></</i> 赞 (${count - 1})`;
                btn.style.color = "";
            }
        });
    });
}

// 绑定发布动态事件
function bindPublishEvent() {
    const publishBtn = document.getElementById("publishPost");
    const postContent = document.getElementById("postContent");

    publishBtn.addEventListener("click", () => {
        const content = postContent.value.trim();
        if (!content) {
            alert("请输入动态内容！");
            return;
        }

        // 模拟发布新动态
        const newFeed = {
            id: mockData.feeds.length + 1,
            type: "text",
            user: { name: "星辰大海", avatar: "assets/images/avatar.jpg" },
            time: "刚刚",
            content: content,
            likes: 0,
            comments: 0,
            shares: 0
        };

        // 添加到数据中并重新加载
        mockData.feeds.unshift(newFeed);
        const activeTab = document.querySelector(".tab-btn.active").dataset.tab;
        loadFeeds(activeTab);

        // 清空输入框
        postContent.value = "";

        // 发布成功提示
        const notification = document.createElement("div");
        notification.style.position = "fixed";
        notification.style.top = "20px";
        notification.style.left = "50%";
        notification.style.transform = "translateX(-50%)";
        notification.style.backgroundColor = "rgba(0,128,0,0.8)";
        notification.style.color = "#fff";
        notification.style.padding = "10px 20px";
        notification.style.borderRadius = "4px";
        notification.style.zIndex = "1000";
        notification.textContent = "动态发布成功！";
        document.body.appendChild(notification);

        // 3秒后移除提示
        setTimeout(() => {
            notification.style.opacity = "0";
            notification.style.transition = "opacity 0.5s";
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 500);
        }, 3000);
    });
}